package com.example.springkotlindemo.controller

import com.example.springkotlindemo.entity.DemoUser
import com.example.springkotlindemo.service.DemoUserService
import kotlinx.coroutines.Dispatchers.Unconfined
import kotlinx.coroutines.delay
import kotlinx.coroutines.reactor.flux
import kotlinx.coroutines.reactor.mono
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RestController
import reactor.core.publisher.Flux

/**
 * @author Xu Haidong
 * @date 2023/4/23 16:44
 */
@RestController
class DemoController {

    private val logger = LoggerFactory.getLogger(this.javaClass)

    @Autowired
    lateinit var demoUserService: DemoUserService

    @GetMapping("test1")
    fun test1() = mono(Unconfined) {
        println("当前线程：${Thread.currentThread().name}")
        doSomething()
        "执行完毕"
    }

    suspend fun doSomething() = delay(10000)

    @GetMapping("listUser")
    fun getUser(): Flux<DemoUser> = flux(Unconfined) {
        val list = demoUserService.list()
        list.forEach {
            channel.send(it)
        }
    }

    @GetMapping("/getById/{userId}")
    fun getById(@PathVariable("userId") userId: Long) = mono(Unconfined) {
        demoUserService.getById(userId)
    }

}